package com.celan.year2023.month01.day12;

import java.util.*;

/**
 * leetcode297
 */

public class Codec {

    public String serialize(TreeNode root) {
        return reSerialize(root, "");
    }

    public TreeNode deserialize(String data) {
        String[] dataArray = data.split(",");
        List<String> dataList = new LinkedList<>(Arrays.asList(dataArray));
        return reDeserialize(dataList);
    }

    public String reSerialize(TreeNode root, String str) {
        if (root == null) {
            str += "None,";
            return str;
        }

        str += root.val + ",";
        str = reSerialize(root.left, str);
        str = reSerialize(root.right, str);
        return str;
    }

    public TreeNode reDeserialize(List<String> dataList) {
        if (dataList.get(0).equals("None")) {
            dataList.remove(0);
            return null;
        }

        TreeNode root = new TreeNode(Integer.parseInt(dataList.get(0)));
        dataList.remove(0);
        root.left = reDeserialize(dataList);
        root.right = reDeserialize(dataList);

        return root;
    }
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}

